<script>
import { isAvailable, isNumber, isObject, value } from '@/utils/kris_utils'
import dayjs from 'dayjs'

export default {
    props:{
        fallback:{
            type:String,
            default:'-'
        },
        isEditing:false,
        fetchDataFn:{
            type:Function,
            default:null
        },
        options:{
            type:Array,
            required:true,
            default(){
                return []
            }
        }
    },
    computed:{
        attrs(){
            const attrs = {...this.$attrs}
            return attrs
        },
        listeners(){
            const listeners = { ...this.$listeners }

            listeners['input'] = this.setValue

            return listeners
        },
        valueFormatted(){
            if(value(this.current,'label',null) === null)
                return this.fallback

            return this.current.label
        },
        onInitDefaultValue(){
            const { options,$attrs:{value} } = this

            return (Array.isArray(options) && options.length > 0) &&
                    isAvailable(value)
        }
    },
    data(){
        return {
            isInited:false,
            current:null
        }
    },
    methods:{
        setValue(value){
            const target = this.options.find(item => item.value === value)
            this.current = target

            this.$emit('input',value)
        }
    },
    watch:{
        '$attrs.value':function(v){
            if(isAvailable(this.$attrs.value))
                this.setValue(this.$attrs.value)
        },
        options(options){
            const target = options.find(item => item.value === this.$attrs.value)
            
            if(!target)
                return

            this.setValue(this.$attrs.value)
        },
        onInitDefaultValue:{
            handler(v){
                if(!v || this.isInited)
                    return
                
                this.isInited = true
                this.setValue(this.$attrs.value)
            },
            immediate:true
        }
    }
}
</script>
<template>
    <el-select
      v-if="isEditing"
      v-bind="attrs"
      v-on="listeners"
    >
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value" 
        />
    </el-select>

    <span v-else>{{ valueFormatted }}</span>
</template>

<style lang="scss">
</style>